//
//  statusPictureView.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/11.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import UIKit
import SDWebImage
let itemPicturnMargin: CGFloat = 8
let statusPictureIdentifier = "pictureCell"
class statusPictureView: UICollectionView {
    init(){
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumInteritemSpacing = itemPicturnMargin
        flowLayout.minimumLineSpacing = itemPicturnMargin
        super.init(frame: CGRectZero, collectionViewLayout: flowLayout)
        backgroundColor = UIColor.whiteColor()
        dataSource = self
        delegate = self
        registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: statusPictureIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
/// 模型数据
    var statusViewModel: StatusViewModel? {
        didSet{
            sizeToFit()
            reloadData()
        }
    }
}

//MARK: - 数据源方法
extension statusPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    ///发送选中的照片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelectedPhotoNotification, object: self, userInfo: [WBStatusSelectorPhotosIndexPathKey:indexPath,WBStatusSelectorPhotosURLsKey:(statusViewModel?.thumbnailArray)!])
        imageViewFromePresent(indexPath)

    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (statusViewModel?.thumbnailArray?.count) ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictureIdentifier, forIndexPath: indexPath) as? StatusPictureCell
        cell?.imageURL = statusViewModel?.thumbnailArray![indexPath.item]
        return cell!
    
    }
}
// MARK: - 过场动画的代理方法
extension statusPictureView : PictureBrowerPresentDeldegate{
    func imageViewFromePresent(indexPath: NSIndexPath) -> UIImageView {
        let iv = UIImageView()
    
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let key = statusViewModel?.thumbnailArray![indexPath.item].absoluteString
        iv.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        iv.sizeToFit()
        return iv
    }
    func PictureBrowerPresentFromRect(indexPath: NSIndexPath) -> CGRect {
        guard let cell = cellForItemAtIndexPath(indexPath) as? StatusPictureCell else{
            
            return CGRectZero
        }
      let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return rect
    }
    func PictureBrowerPresenttoRect(indexPath: NSIndexPath) -> CGRect {
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(statusViewModel?.thumbnailArray![indexPath.item].absoluteString) else{
            return CGRectZero
        }
        let Height = UIScreen.mainScreen().bounds.height
        let width = UIScreen.mainScreen().bounds.width
        var y: CGFloat = 0
        let height = image.size.height * width / image.size.width
        if height < Height{
            y = (Height - height) * 0.5
        }
        let rect = CGRect(x: 0, y: y, width: width, height: height)
        return rect
    }
    
    
}
// MARK: - 计算时间大小
extension statusPictureView {
    private func calcViewSize()->CGSize{
     let rowCount: CGFloat = 3
     let maxWidth = UIScreen.mainScreen().bounds.size.width - CGFloat(statusCellMargin) * 2.0
     let itemWidth = (maxWidth - 2 * itemPicturnMargin) / rowCount
     let count = statusViewModel?.thumbnailArray?.count ?? 0
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        if count == 0{
            layout.itemSize = CGSizeMake(1, 1)
            return CGSizeZero
        }
        if count == 1{
            var size = CGSizeMake(150, 120)
            let key = statusViewModel?.thumbnailArray?.first?.absoluteString
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key){
                size = image.size
            }
           size.width  = size.width < 40 ? 40 : size.width
            if size.width > 300{
                let w: CGFloat = 300
                let h = size.height * w / size.width
                
                size = CGSize(width: w, height: h)
            }
            layout.itemSize = size
            return size
        }
        if count == 4{
            let w = 2 * itemWidth + itemPicturnMargin
            return CGSizeMake(w, w)
        }
        
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let height = row * itemWidth + (row - 1) * itemPicturnMargin
        return CGSizeMake(maxWidth, height)
    }
}
private class  StatusPictureCell: UICollectionViewCell{
    lazy var iconView : UIImageView = {
        let img = UIImageView()
        img.contentMode = .ScaleAspectFill
        img.clipsToBounds = true
        return img
    }()
    var imageURL : NSURL?{
        didSet{
            iconView.sd_setImageWithURL(imageURL, placeholderImage: nil, options: [SDWebImageOptions.RefreshCached,SDWebImageOptions.RetryFailed])
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupUI(){
        contentView.addSubview(iconView)
    }
    
}








